package com.iwithlong.merchantcontroller;

import com.imesne.assistant.common.runtime.RunBinder;
import com.iwithlong.annotation.MerchantSession;
import com.iwithlong.context.Constants;
import com.iwithlong.context.ResultConst;
import com.iwithlong.service.MerchantService;
import com.iwithlong.vo.MerchantVo;
import com.ktanx.platform.admin.controller.AdminBaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 商户h5页面接口
 * Created by mhy on 2018/6/10.
 */

@Controller
@RequestMapping("/merchant")
public class MerchantLoginController extends AdminBaseController {
    @Resource
    private MerchantService merchantService;

    /**
     * 登陆页
     * @return
     */
    @RequestMapping(value = {"","login"})
    public String login(){
        return "merchantH5/login";
    }

    /**
     * 登陆
     * @param merchantVo
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("logon")
    public String logon(MerchantVo merchantVo,HttpServletRequest request,Model model){
        MerchantVo loginMerchant = merchantService.logon(merchantVo.getMemberCode(),merchantVo.getMemberPassword());
        if(RunBinder.hasErrors()){
            model.addAttribute(ResultConst.MESSAGE,RunBinder.getStrErrors());
            model.addAttribute("merchantVo",merchantVo);
            return "merchantH5/login";
        }else {
            request.getSession().setAttribute(Constants.LOGIN_MERCHANT,loginMerchant);
            return "merchantH5/main";
        }
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @MerchantSession
    @RequestMapping("logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute(Constants.LOGIN_MERCHANT);
        return "merchantH5/login";
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param request
     * @param modelMap
     * @return
     */
    @MerchantSession
    @RequestMapping("modifyPwd.json")
    public String modifyPwd(String oldPassword,String newPassword,HttpServletRequest request,ModelMap modelMap){
        MerchantVo merchantVo = (MerchantVo)request.getSession().getAttribute(Constants.LOGIN_MERCHANT);
        merchantService.modifyPwd(merchantVo.getMemberCode(),oldPassword,newPassword);
        procelJsonModel(modelMap);
        return "";
    }

    private void procelJsonModel(ModelMap modelMap){
        if(RunBinder.hasErrors()){
            modelMap.addAttribute(ResultConst.SUCCESS,false);
            modelMap.addAttribute(ResultConst.MESSAGE,RunBinder.getStrErrors());
        }else {
            modelMap.addAttribute(ResultConst.SUCCESS,true);
        }
    }


}
